addnode()
{
    lockfile $1.lock
    echo "$2" >> $1
    rm -f $1.lock
}

check_stop_condition()
{
    stopping=$1
    logging=$2
    if [[ -e ${stopping} ]]; then
        echo -e "[$(date)] File \"${stopping}\" detected. Exiting... (tasks will not be interrupted)" >> ${logging}
        exit
    fi
}

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#
#@@   CHOOSE THE INPUT VARIABLES       @@#
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#

DO_VALENCE_ANALISIS="yes"
DO_CHIRAL_SEA="no"
DO_P2FIT="no"

#Gamma and Momentum order convention
#gamma="TWISTED"
#momentum_order="TXYZ"
#convention="TW"

gamma="APE"
momentum_order="TYZX"
convention="APE"



# Directories
dirreno="/home/nucave/workdir/lattice/RENORMALIZATION/reno"

dir="$dirreno/NF4/Z4F/"
dirinput="$dirreno/NF4/Z4F/INPUT"

dirdata="/home/nucave/workdir/lattice/RENORMALIZATION/"

#Gauge Fixing and Gauge Action
gauge_fixing="landau"
gauge_action="iwasaki"

# Fermionic Action
Nf=4
action="TwistedMass"

#Choose beta (beta*100)
beta100=195

#Choose L, T | L^3xT=V
L=24
T=48

#Nr=2 -> r0 & r1
Nr=2


#Choose ensemble List
eList=(2)

#Choose theta: p, m
pmList=("m")

# NOa2=1 : uncor
# NOa2=2 : uncor+Oa2g2
# NOa2=3 : uncor+Oa2g2+Oa2g2b

#corrOa2print="no"
#NOa2=1

corrOa2print="yes"
NOa2=3


# Choose: Nmom, conf_ini, jump, Nclust, Nex

if [ $beta100 -eq 195 ]
then
ainv=2.5234
Nmom=139
fi
if [ $beta100 -eq 210 ]
then
ainv=3.16
Nmom=491
jump=1
Nclust=6
Nex=16
conf_ini=100
fi


######################
## $dirinput/mom.dat file
########################
echo "1 0 0 0" > $dirinput/mom.dat # boundary conditions
echo "2" >> $dirinput/mom.dat # Nindexmom
if [ $Nmom -eq 139 ]
then
echo "0 3 0 2 0 2 0 2" >> $dirinput/mom.dat
echo "4 7 2 3 2 3 2 3" >> $dirinput/mom.dat
fi
if [ $Nmom -eq 491 ]
then
echo "0 3 0 2 0 2 0 2" >> $dirinput/mom.dat
echo "4 9 2 5 2 5 2 5" >> $dirinput/mom.dat
fi

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#


beta=$(echo "scale=2; $beta100/100" | bc -l)

sed "s/__GAMMA__/$gamma/g;s/__MOMENTUM_ORDER__/$momentum_order/g" $dirreno/SRC/base_template.h > $dirreno/SRC/base.h
source ~/workdir/root/bin/thisroot.sh


if [ $DO_VALENCE_ANALISIS = "yes" ]
then
sh compile.sh Calc_Z4F_oneP
for e in  ${eList[*]}
do
    if [ $beta100 -eq 195 ]
    then
  	if [ $e -eq 2 ] 
	then 
		conf_ini=105
		Nclust=23
		Nex=16
		jump=4
                Uplaq=0.58
	fi
     fi
     #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#
     #@@  CHOOSE THE NUMBER OF MASSES TO BE ANALYSED  @@#
     #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#
     if [ $beta100 -eq 210 ]
     then 
        Uplaq=0.6133375

	if [ $e -eq 3 ]
	then
               massList=(0.0025 0.0046 0.0090 0.0152 0.0201 0.0249 0.0297)
               mPCAC=(0.00559 -0.00585)
	fi
        if [ $e -eq 5 ]
        then
               massList=(0.0048  0.0078  0.0119  0.0190  0.0242  0.0293)
               mPCAC=(0.00829 0.00823)
        fi

      fi

      if [ $beta100 -eq 195 ]
      then
	Uplaq=0.58
	if [ $e -eq 2 ]
	then
               # mass list
               massList=(0.0085 0.015 0.0203 0.0252 0.0298)
               # mPCAC val (p,m)
               mPCAC=(0.0203 -0.0213)

	fi
     fi

	for pm in ${pmList[*]}
	do
		epm=${e}${pm}
		echo "@@@@@@@@@@@@@@@@@@@@@@@"
		echo "@@  ensemble=$epm   @@"
		echo "@@@@@@@@@@@@@@@@@@@@@@"
		
		#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#
		#@@  CHOOSE THE kappa_sea                        @@#
		#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#

		if [ $beta100 -eq 195 ]
		then
			if [ ${epm} = "2m" ] ; then kappa_sea="0.161229" ; fi
		fi
                if [ $beta100 -eq 210 ]
                then
                        if [ ${epm} = "3m" ] ; then kappa_sea="0.156209" ; fi
                        if [ ${epm} = "3p" ] ; then kappa_sea="0.156017" ; fi
                        if [ ${epm} = "5m" ] ; then kappa_sea="0.156291" ; fi
                        if [ ${epm} = "5p" ] ; then kappa_sea="0.155949" ; fi
                fi


		#create dirs
		if [ $convention = "APE" ]
		then
	              dir_input="$dirdata/DATA/INPUT-APE/${action}Nf${Nf}/b$beta100/${e}${pm}/"
        	      dir_output="$dirdata/DATA/OUTPUT-APE/${action}Nf${Nf}/b$beta100/Z4F/${e}${pm}/"
		else
	              dir_input="$dirdata/DATA/INPUT/${action}Nf${Nf}/b$beta100/${e}${pm}/"
		      dir_output="$dirdata/DATA/OUTPUT/${action}Nf${Nf}/b$beta100/Z4F/${e}${pm}/"
		fi
		mkdir -p -v $dir_output/Z_ALLP
		mkdir -p -v $dir_output/FF_ALLP
                mkdir -p -v $dir_output/LAMBDA_ALLP
		for i in `seq 0 $Nmom`; do imom=`printf %03d $i`; mkdir -p -v $dir_output/p$imom ; done
		for rcomb in 0001 1110 ; do for i in `seq 0 $Nmom`; do imom=`printf %03d $i`; mkdir -p -v $dir_output/$rcomb/p$imom ; done ; done

		##############################
		# INPUT OF THE PROGRAMS
		##############################
                Nmass=${#massList[*]}
                echo $Nmass > $dirinput/mu.dat
                for im in `seq 1 $Nmass`
                do
                                mass=${massList[$(echo " $im -1 " |bc -l )]}
                                echo $mass >> $dirinput/mu.dat
                 done
                 rm $dirinput/mPCAC.dat
                 # write in the correct order
                 if [ $pm = "p" ] ; then echo ${mPCAC[0]} >> $dirinput/mPCAC.dat ;fi
                 if [ $pm = "m" ] ; then echo ${mPCAC[1]} >> $dirinput/mPCAC.dat ;fi

		echo $L > $dirinput/input.dat
		echo $T >> $dirinput/input.dat
		echo $Nclust >> $dirinput/input.dat
		echo $dir_output >> $dirinput/input.dat


		if [ $corrOa2print = "yes" ] ; then corrOa2=1  ; else corrOa2=0  ; fi
		echo $corrOa2 > $dirinput/Oa2.dat
		echo "$NOa2">> $dirinput/Oa2.dat

		args="-Nf=$Nf -beta100=${beta100} -L=$L -T=$T -e=$e -dir_input=$dir_input -dir_output=$dir_output -kappa_sea=$kappa_sea -conf_ini=${conf_ini} -jump=${jump} -Nclust=${Nclust} -Nex=${Nex} -Nmass=$Nmass -Nr=${Nr} -beta=${beta} -Uplaq=${Uplaq} -NOa2=${NOa2} -gauge_fixing=${gauge_fixing} -gauge_action=${gauge_action}"
		echo $args > $dir/EXECUTABLES/args 

		log="log.Calc_Z4F.$(date +%d%b%Y-%Hh%Mm)"
		script="launch_Z4F_onemomenta.sh"
		executable="Calc_Z4F_oneP"
		list="todo_list.Calc_Z4F"
		nodes="nodes.Calc_Z4F"
		stopping=".parate"


		while [[ -s ${list} ]]; do
			check_stop_condition ${stopping} ${log}
			if [[ -s ${nodes} ]]; then

        			# choosing an empty slot
		        	lockfile ${nodes}.lock
			        slot=$(cat ${nodes}|sed -e '1!D')
			        sed -e '1D' ${nodes} > ${nodes}.temp
			        mv ${nodes}.temp ${nodes}
		        	rm -f ${nodes}.lock

			        # reading the task
			        lockfile ${list}.lock
			        task=$(cat ${list} | sed -e '1!D')
		        	sed -e '1D' ${list} > ${list}.temp
			        mv ${list}.temp ${list}
			        rm -f ${list}.lock
	
			        if [[ -n ${task} ]]; then
                			imom=$(echo ${task} | awk  '{print $1}')
					imass=$(echo ${task} | awk  '{print $2}')
					irc=$(echo ${task} | awk  '{print $3}')
					jmom=`printf %03d $imom`
        			else
			            addnode ${nodes} ${slot}
			            slot=""
			            sleep 1m
			        fi

    			else
        			slot=""
			        sleep 1m
			fi


			 #################################
			 # launch the task
			 #################################

			 if [[ -n ${slot} ]]; then

            			inode=$(echo ${slot} | awk -F"cpu" '{print $1}')
			        icpu=$(echo ${slot} | awk -F"${inode}" '{print $2}')
			
            			ssh ${inode} "sh ${dir}/SCRIPTS/Calc_Z4F/${script} args $imom $imass $irc $log $slot $nodes &> $dir/LOGS/Calc_Z4F_${jmom}_m${imass}_rc${irc}_${slot}.log  2>&1 & "


		                lockfile ${log}.lock
		                echo -e " ${slot}  beta=${beta} -- ensemble=${epm} --- p:${jmom} m:${imass} rc:${irc} --- In_progress" >> ${log}
		                rm -f ${log}.lock
		 	        sleep 1m
		        fi
		done
	


		#######################


	done # pmList
done #eList
fi

############################
## SEA CHIRAL LIMIT
###########################
if [ $DO_CHIRAL_SEA = "yes" ]
then
#add the suffix of the rgi you want to analyse
#rgi=""
rgi="_RIp_ainv"
for pm in ${pmList[*]}
do

	# input sea
        echo $L > $dirinput/inputsea.dat
        echo $T >> $dirinput/inputsea.dat
        echo $Nclust >> $dirinput/inputsea.dat
        echo $pm >> $dirinput/inputsea.dat
        echo "$dirdata/DATA/OUTPUT/${action}Nf${Nf}/b$beta100/" >> $dirinput/inputsea.dat
	echo $rgi >>$dirinput/inputsea.dat

	for i in `seq 0 $Nmom`; do imom=`printf %03d $i`; mkdir -p  -v $dirdata/DATA/OUTPUT/${action}Nf${Nf}/b$beta100/$pm/p$imom/ ; done

        if [ $corrOa2print = "yes" ] ; then corrOa2=1  ; else corrOa2=0  ; fi
        echo $corrOa2 > $dirinput/Oa2.dat
        echo "$NOa2">> $dirinput/Oa2.dat
	

	sea_massList=(0.0046 0.0078)
	sea_ensembleList=(3 5)
	if [ $pm = "m" ] ; then sea_mpcacList=(-0.00585 -0.00823); fi
	if [ $pm = "p" ] ; then sea_mpcacList=(0.00559 0.00829) ; fi

        seaNmass=${#sea_massList[*]}
        echo $seaNmass > $dirinput/musea.dat
        for im in `seq 1 $seaNmass`; do ensemble=${sea_ensembleList[$(echo " $im -1 " |bc -l )]}; echo $ensemble >> $dirinput/musea.dat; done
	for im in `seq 1 $seaNmass`; do  mass=${sea_massList[$(echo " $im -1 " |bc -l )]}; echo $mass >> $dirinput/musea.dat; done
	for im in `seq 1 $seaNmass`; do mPCAC=${sea_mpcacList[$(echo " $im -1 " |bc -l )]}; echo $mPCAC >> $dirinput/musea.dat; done
	
	
	time for i in `seq 0 $Nmom`; do echo $i> $dirinput/imom.dat; imom=`printf %03d $i`; echo "p$imom";  root -q -b -l Z_CHIRALSEA.c ; done
done # pm
fi

#############################
## p2 fit & pm average
#############################
if [ $DO_P2FIT = "yes" ]
then

#rgi=""
rgiList=("_RIp_ainv")

# p2 cuts
p2min_lin=1.5
p2max_lin=2.2

p2min_av=1.1
p2max_av=1.23

cut=0.28

# create directory
for pm in p m a ; do mkdir -p $dirdata/DATA/OUTPUT/${action}Nf${Nf}/b$beta100/$pm/Z_ALLP/ ; done
for j in 1 2 ; do mkdir -p $dirdata/DATA/OUTPUT/${action}Nf${Nf}/b$beta100/a/p2FIT/M$j ; done

for rgi in ${rgiList[*]}
do

        # input sea
        echo $L > $dirinput/inputfit.dat
        echo $T >> $dirinput/inputfit.dat
	echo "$p2min_lin $p2max_lin" >> $dirinput/inputfit.dat
	echo "$p2min_av $p2max_av" >>$dirinput/inputfit.dat
	echo "$cut" >>$dirinput/inputfit.dat
        echo $Nclust >> $dirinput/inputfit.dat
        echo "$dirdata/DATA/OUTPUT/${action}Nf${Nf}/b$beta100/" >> $dirinput/inputfit.dat
        echo $rgi >>$dirinput/inputfit.dat


        if [ $corrOa2print = "yes" ] ; then corrOa2=1  ; else corrOa2=0  ; fi
        echo $corrOa2 > $dirinput/Oa2.dat
        echo "$NOa2">> $dirinput/Oa2.dat

	time root -q -b -l p2FIT.c 

done # rgi
fi

cd $dir
